package com.gitee.candy.utils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author suyanlong
 * @Version V1.0.0
 * @Date 2021/9/25 21:44
 * @Description LRU内存缓存
 */
public class CacheUtils {

    public static void main(String[] args) {
        set(1, "0000");
        set("123", new Node(), 3);
        set("456", 12346, 5);

        System.out.println(get(1) instanceof String);
        System.out.println(get("123") instanceof Node);
        System.out.println(get("456") instanceof Integer);
    }

    static Map<Object, Node> data = new ConcurrentHashMap<>();

    public static void set(Object key, Object value) {
        set(key, value, 0);
    }

    public static void set(Object key, Object value, Integer expireTime) {
        expireTime = 1000 * expireTime;
        long currentTimeMillis = System.currentTimeMillis();
        Node node = new Node(key, value, currentTimeMillis, currentTimeMillis + expireTime.longValue());
        data.put(key, node);
    }

    public static Object get(Object key) {
        Node node = data.get(key);
        if (node != null) {
            if (node.cacheTime == node.expireTime) {
                // 永久缓存
                return node.getValue();
            } else if (node.expireTime < System.currentTimeMillis()) {
                // 过期
                data.remove(key);
            } else {
                return node.getValue();
            }
        }
        return null;
    }

    static class Node {
        private Object key;
        private Object value;
        private long cacheTime;
        private long expireTime;

        Node() {
        }

        public Node(Object key, Object value, long cacheTime, long expireTime) {
            this.key = key;
            this.value = value;
            this.cacheTime = cacheTime;
            this.expireTime = expireTime;
        }

        public Object getKey() {
            return key;
        }

        public void setKey(Object key) {
            this.key = key;
        }

        public Object getValue() {
            return value;
        }

        public void setValue(Object value) {
            this.value = value;
        }

        public long getCacheTime() {
            return cacheTime;
        }

        public void setCacheTime(long cacheTime) {
            this.cacheTime = cacheTime;
        }

        public long getExpireTime() {
            return expireTime;
        }

        public void setExpireTime(long expireTime) {
            this.expireTime = expireTime;
        }
    }
}
